package ua.diploma.hibernate.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import ua.diploma.hibernate.dto.SecretQuestion;
import ua.diploma.hibernate.util.HibernateUtil;

/**
 * ДАО для работы с таблицей секретных вопросов
 * 
 * @author netstalk3r
 * 
 */
public class SecretQuestionDAOImpl implements SecretQuestionDAO {

	@Override
	public void addSecretQuestion(SecretQuestion secretQuestion)
			throws SQLException {
		Session session = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(secretQuestion);
			session.getTransaction().commit();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}

	@Override
	public void updateSecretQuestion(SecretQuestion secretQuestion)
			throws SQLException {
		Session session = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(secretQuestion);
			session.getTransaction().commit();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SecretQuestion> getAllSecretQuestion() throws SQLException {
		Session session = null;
		List<SecretQuestion> secretQuestions = new ArrayList<SecretQuestion>();
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			secretQuestions = ((List<SecretQuestion>) session.createQuery(
					"FROM SecretQuestion").list());
			session.getTransaction().commit();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return secretQuestions;
	}

	@Override
	public void deleteSecretQuestion(SecretQuestion secretQuestion)
			throws SQLException {
		Session session = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(secretQuestion);
			session.getTransaction().commit();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}

	@Override
	public SecretQuestion getSecretQuestionById(Integer id) throws SQLException {
		Session session = null;
		SecretQuestion secretQuestion = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			secretQuestion = (SecretQuestion) session
					.createQuery("FROM SecretQuestion WHERE id = :id")
					.setParameter("id", id).uniqueResult();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return secretQuestion;
	}

}
